import React, { Component } from 'react';
import ReactEcharts from "echarts-for-react";
import "echarts/lib/chart/line";
import "echarts/lib/component/tooltip";
import "echarts/lib/component/title"; // 此处是按需引入
import textfile from "./data/text_vectors_afterNormalize/output.txt"
import emitter from './utils/events'
import { clusterSearch } from './api/api';

// var dataPath = '../data/text_vectors_afterNormalize'


class EchartLine extends Component {
    echartRef = {}
    constructor(props) {
        super(props);
        this.state= {
           data:[],
           mark:['阴虚', '肝胆','皮肉外伤','风寒头痛','大小便疾病','妇产疾病','儿科疾病','气胀水肿','哽咽','肺系疾病','眼科疾病','耳鼻喉科','疮痈肿毒','内科','14'],
           colors:["#5e904e", "#7b038e", "#0ca82e", "#e81659", "#0b5313", "#0494fb", "#304866", "#c667f3", "#513886", "#239eb3", "#972b2d", "#ba865c", "#76480d", "#dd6e81"]
        }
    }
    componentDidMount() {
      // 组件装载完成以后声明一个自定义事件
      const data = []
      for(var i = 0 ; i < 14 ; i ++){
        var newarray = []
        data.push(newarray)
      }
      fetch(textfile)
      .then((r) => r.text())
      .then(text  => {
        var lines = text.split('\n')
        for(var i = 0 ; i < lines.length ; i++){
          var line = lines[i].split(',')
          data[Number(line[0])].push([Number(line[1]),Number(line[2]),line[3]])
        }
        this.setState({data:data})
        debugger
      }).then(()=>console.log(this.state.data))

      this.eventEmitter = emitter.addListener('addHighLightNodes', (message) => {
        let curOptions = this.echartRef.getEchartsInstance().getOption()
        curOptions["series"].push({
          name: "相关节点",
          type: 'scatter',
          symbolSize:"10",
          color:"#010101",
          // emphasis: {
          //   focus: 'series'
          // },
          // prettier-ignore
          
          data: message.highlight_nodes.map((item,k) =>{
            debugger
            return [Number(item['x']),Number(item['y']),item['name']]
          })

        })
        this.echartRef.getEchartsInstance().setOption(curOptions)
      });
  }
  componentWillUnmount() {
      emitter.removeListener(this.eventEmitter);
  }



    getOption = () => {
      // 组装数据，返回配置 option
      
      
      return {
        title: {
          text: '',
          subtext: ''
        },
        grid: {
          left: '3%',
          right: '7%',
          bottom: '7%',
          containLabel: true
        },
        tooltip: {
          // trigger: 'axis',
          showDelay: 0,
          formatter: function (params) {
            // if (params.value.length > 1) {
              return (
                params.value[2]
              );
            // } else {
            //   return (
            //     params.seriesName +
            //     ' :<br/>' +
            //     params.name +
            //     ' : ' +
            //     params.value +
            //     'kg '
            //   );
            // }
          },
        },
        toolbox: {
          feature: {
            dataZoom: {},
            brush: {
              type: ['rect', 'polygon', 'clear']
            }
          }
        },
        brush: {},
        legend: {
          data: this.state.mark,
          left: 'center',
          bottom: 10
        },
        xAxis: [
          {
            show:false,
            type: 'value',
            scale: true,
            axisLabel: {
              formatter: '{value}'
            },
            splitLine: {
              show: false
            }
          }
        ],
        yAxis: [
          {
            show:false,
            type: 'value',
            scale: true,
            axisLabel: {
              formatter: '{value}'
            },
            splitLine: {
              show: false
            }
          }
        ],
        // series : this.state.data
        series: this.state.data.map(( items , i)=>{
          return (
            {
              name: this.state.mark[i],
              type: 'scatter',
              color :this.state.colors[i],
              // emphasis: {
              //   focus: 'series'
              // },
              // prettier-ignore
              data : items
              // data: items.map((item,k) =>{
              //   return [Number(item[0]),Number(item[1]),item[2]]
              // })

            }
          )
        })
      }
  };
  
  cSearch = async (params) =>{
    debugger
    let res = await clusterSearch({node:params.data[2]})
    let emphasisData = {}
    emphasisData['x'] = params.data[0]
    emphasisData['y'] = params.data[1]
    emphasisData['name'] = params.data[2]
    emitter.emit("addHighLightNodes",{highlight_nodes:[emphasisData]})

    if(res.code == 200){
      emitter.emit("appendPrescription",{data:res.data})
    }
  }

  render() {
    let EventsDict = {
      'click':(params)=>{
        this.cSearch(params)
        
      },
    }
    return(
      
      <ReactEcharts
      ref={e => this.echartRef = e}
        style={{height:"100%"}}
        option={this.getOption()}
        notMerge
        lazyUpdate
        theme={"theme_name"}
        // onChartReady={this.onChartReadyCallback}
        onEvents={EventsDict}
      />
    )
  }
}
 
export default EchartLine;